package com.huitone.smspfm.oldclient.core;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.IOUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.huitone.smspfm.oldclient.app.AppStaticConfigs;
import com.huitone.smspfm.oldclient.logger.ExtLogger;
import com.huitone.smspfm.oldclient.model.RecvSms;

public class WebServiceClient {
	private final static ExtLogger logger = ExtLogger.create(WebServiceClient.class);

	private static String params = null;
	
	private final static String default_params = "<?xml version=\"1.0\" encoding=\"utf-8\"?> "
			+"<soapenv:Envelope "
     		+ "xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" "
     		+ "xmlns:mk=\"http://mk.gd.soa.csg.cn\">    "
     		+ "<soapenv:Header/>    "
     		+ "<soapenv:Body>       "
     		+ "<mk:I_DXPT_DXJSRequest>          "
             		+ "<mk:FW_DXJS_IN>             "
	             		+ "<mk:XLHM>%s</mk:XLHM>            "
	             		+ "<mk:FSDK>%s</mk:FSDK>             "
	             		+ "<mk:SJFSSJ>%s</mk:SJFSSJ>             "
	             		+ "<mk:DXNR>%s</mk:DXNR>             "
	             		+ "<mk:KHZH>%s</mk:KHZH>          "
             		+ "</mk:FW_DXJS_IN>       "
     		+ "</mk:I_DXPT_DXJSRequest>    "
     		+ "</soapenv:Body> "
     		+ "</soapenv:Envelope> "; 
	
	
	public static Map<String,Object> recvSmsWebService(RecvSms recvSms) throws Exception {
		 
		if(params==null){
			params = getParams();
			params = String.format(params, recvSms.getSerialno(),recvSms.getSendport(),recvSms.getCrttime(),recvSms.getContent(),recvSms.getMobileno());
		}
		
		String webServiceUrl = AppStaticConfigs.smsRecvWebServiceUrl;
		  URL url = new URL(webServiceUrl);  
	        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();//打开连接  
	  
	        //Content-Length长度会自动进行计算  
	        httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");  
	        httpConn.setRequestProperty("soapAction",webServiceUrl.split("\\?")[0]);//Soap1.1使用 其实完全可以不需要  
	        httpConn.setRequestMethod("POST");  
	        httpConn.setDoOutput(true);  
	        httpConn.setDoInput(true);  
	  
	        OutputStream out = httpConn.getOutputStream();  
	  
	        out.write(params.getBytes("utf-8"));  
	        out.close();  
	  
	        if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK)  
	        {  
	            InputStreamReader is = new InputStreamReader(httpConn.getInputStream());  
	            BufferedReader in = new BufferedReader(is); 
	            StringBuffer buffer = new StringBuffer();
	            String inputLine;  
	            while ((inputLine = in.readLine()) != null)  
	            {  
	            	buffer.append(inputLine);
	            }  
	            in.close();  
	            httpConn.disconnect();
	            return parse(buffer.toString());
	        }  
	        else{  
	            //如果服务器返回的HTTP状态不是HTTP_OK，则表示发生了错误，此时可以通过如下方法了解错误原因。  
	            InputStream is = httpConn.getErrorStream();    //通过getErrorStream了解错误的详情，因为错误详情也以XML格式返回，因此也可以用JDOM来获取。  
	            InputStreamReader isr = new InputStreamReader(is,"utf-8");  
	            BufferedReader in = new BufferedReader(isr);
	            StringBuffer buffer = new StringBuffer();
	            String inputLine;  
	            while ((inputLine = in.readLine()) != null)  
	            {  
	            	buffer.append(inputLine);
	            }  
	            in.close();  
	            httpConn.disconnect(); 
	            logger.error("接口调用失败:"+ buffer.toString());
	            return null;
	        }  
	}
	
	
	
	  
	    public  static Map<String,Object> parse(String soap) throws DocumentException {
	    	Map<String,Object> map = new HashMap<>();
	        Document doc = DocumentHelper.parseText(soap);//报文转成doc对象
	        Element root = doc.getRootElement();//获取根元素，准备递归解析这个XML树
	        getCode(root,map);
	        return map;
	    }

	    public  static void getCode(Element root,Map<String,Object> map){
	        if(root.elements()!=null){
	            List<Element> list = root.elements();//如果当前跟节点有子节点，找到子节点
	            for(Element e:list){//遍历每个节点
	                if(e.elements().size()>0){
	                    getCode(e,map);//当前节点不为空的话，递归遍历子节点；
	                }
	                if(e.elements().size()==0){
	                    map.put(e.getName(), e.getTextTrim());
	                }//如果为叶子节点，那么直接把名字和值放入map
	            }
	        }
	    }
	    
	    public static String getParams() throws Exception{
			FileInputStream input = null;
			try {
				input = new FileInputStream(System.getProperty("dxjs.xml"));
				String params = IOUtils.toString(input,"utf-8");
				input.close();
				return params;
			} catch (IOException e) {
				if(input!=null){
					input.close();
				}
				logger.error("加载DXJS.xml文件错误,使用默认的参数格式！");
				e.printStackTrace();
				return default_params;
		}
	   }
}
